// pages/duBanAdd/duBanAdd.js
import WxValidate from '../../utils/WxValidate.js';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    url: app.globalData.url,
	  workType:0,//工作类型   0 内部工作    1：信访工作
    title:'',
	  emergyType:1,//紧急程度 0：一般    1：紧急    2：加急
    userIds:[],
    joinlist: [],//指派给
    fileIds:[],
	  attachmentList:[
		  
	  ],//附件列表
	  visit:'',
	},
	//选择完成时间
	bindDateChange:function(e){
		this.setData({
			date:e.detail.value
		})
	},
  uploadFujian(){//上传附件
    const _this = this; 
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        wx.showToast({
          title: '上传中。。。',
          icon: 'loading',
          duration: 1500
        })
        wx.uploadFile({
          url: app.globalData.url +'/file/upload', //上传图片接口
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          },
          success(res) {
            const data = JSON.parse(res.data);
            var _attachmentList = _this.data.attachmentList || []; 
            console.log(data);
            _attachmentList.push({
              id: data.data.id,
              name: data.data.srcname, 
              src: app.globalData.url + '/file/showImage/' + data.data.id
            })
            _this.setData({//上传成功后，加入附件列表展示
              attachmentList:_attachmentList
            })
            wx.showToast({
              title: '上传成功',
              icon: 'loading',
              duration: 1000
            })
          },
          fail(res){
            console.log(res);      
            wx.showToast({
              title: '上传失败',
              icon: 'loading',
              duration: 1000
            })      
          }
        })
      }
    })
  },
	//删除附件
	delAttachment:function(e){
		var attachmentList = this.data.attachmentList;//指派列表
		var index = e.currentTarget.dataset.index;
		attachmentList.splice(index, 1);
		this.setData({
			attachmentList: attachmentList
		}) 
	},
	//删除指派人
	delZhiPai:function(e){
		var joinlist = this.data.joinlist;//指派列表
		var index = e.currentTarget.dataset.index;
		joinlist.splice(index,1);
		this.setData({
			joinlist: joinlist
		})
	},
	//选择工作类型
	changeWordType:function(e){
		var index = e.currentTarget.dataset.index;//
		this.setData({
			workType:index
		})
	},
	//选择紧急程度
	changeEmergecy:function(e){
		var index = e.currentTarget.dataset.index;//
		this.setData({
			emergyType: index
		})
	},
	//去选择指派给
	goYuhuiren: function (e) {
		wx.navigateTo({
      url: '../yuHuiRen/yuHuiRen?userIds=' + this.data.userIds,
		})
	},
  changeTitle(e){
    // console.log(e.detail.value);
    this.setData({
      title: e.detail.value
    })
  },
  //报错 
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //验证函数
  initValidate() {
    const rules = {
      // workTitle: {
      //   required: true,
      // },
      date: {
        required: true
      },
      content: {
        required: true,
      }
    }
    const messages = {
      // workTitle: {
      //   required: '请输入工作标题'
      // },
      date: {
        required: '请选择完成日期'
      },
      content: {
        required: '请输入工作要求',
      }
    }
    this.WxValidate = new WxValidate(rules, messages);
  },
  // 表单提交
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    var _this = this;
    var params = e.detail.value
    
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    } else if (this.data.joinlist.length < 1) {
      this.showModal({ msg: "请至少选择1位与会人" })
    } else{
      if (this.data.workType == 0 && this.data.title ==''){
        // console.log("00000000000" + this.data.workTitle+"0000"+this.data.workTitle=="");
        this.showModal({ msg: "请输入工作标题" })
        return false;
      }
      }
     params['type'] = _this.data.workType;
    if (this.data.joinlist != null) {
      var userIds=[];
      for (var i = 0; i < _this.data.joinlist.length; i++) {
        userIds.push({ userId: _this.data.joinlist[i].id});
      }
      params['supervisionUserList'] = userIds;
    }
    if (this.data.attachmentList != null) {
      var fileIds = [];

      for (var i = 0; i < _this.data.attachmentList.length; i++) {
        fileIds.push(_this.data.attachmentList[i].id);
      }
      params['fileIds'] = fileIds;
    }
    params['urgencyDegree'] = _this.data.emergyType;
    params['completeTime'] = _this.data.date;
    params['type'] = Number(_this.data.workType)+1;
    var url = app.globalData.url + '/supervise/saveInfo';
    if (_this.data.workType == 0){
      if (_this.data.id != null && _this.data.id!=''){
        params['id'] = _this.data.id;
        url = app.globalData.url + '/supervise/updateInfo';
      }
    }else
    if (_this.data.workType==1){
      url = app.globalData.url + '/supervise/updateInfo';
      params['id'] = _this.data.visit.id;
     }
      
      wx.request({
        url: url,//创建督办接口
        header: app.header(),
        data: params,
        method: 'POST',
        success: function (res) {
          if (res.statusCode == 405) {
            app.getLogout();
            return;
          }
          console.log(res);
          if (res.data.status=='error') {
            wx.showToast({
              title: res.data.data.content,
              icon: 'loading',
              duration: 1500
            })
          } else {
            wx.showToast({
              title: '保存成功',//这里打印出登录成功
              icon: 'success',
              duration: 1000,
              success: function () {
                console.log('haha');
                setTimeout(function () {
                  //要延时执行的代码
                  wx.switchTab({
                    url: '../wode/wode'
                  })
                }, 2000) //延迟时间
              }
            })
          }
        }
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    this.initValidate()
    var id =options.id;
    if(id!=null){
      wx.setNavigationBarTitle({
        title: '修改督办'//页面标题为路由参数
      })
      wx.request({
		header: app.header(),
        url: app.globalData.url + '/supervise/getInfo/'+id,//创建督办接口
        method: 'GET',
        success: function (res) {
          if (res.statusCode == 405) {
            app.getLogout();
            return;
           }
          console.log(res);
          if(res.data.status=='success'){
            var d = res.data.result;
            var type = Number(d.type) - 1;
            var users = d.supervisionUserList;
            if(users!=null){
            for(var i=0;i<users.length;i++){
              users[i]['fileAction'] = '/file/showImage/'+users[i]['headImage'];
            }
            }
            _this.setData({
              id:d.id,
              title: d.title,
              workType: type,//工作类型   0 内部工作    1：信访工作
              workTitle: d.title,
              emergyType: d.urgencyDegree,//紧急程度 0：一般    1：紧急    2：加急
              userIds: [],
              joinlist: users,//指派给
              date: d.completeTime,
              attachmentList:d.files,//附件列表 
              content:d.content
            })
          }
        }
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})